﻿@using System.Web.Script.Serialization
@{
    ViewBag.Title = "Status";
}
@Styles.Render("~/content/statuses.css")


 
    <div class="row postcontent ">
        <div class="col-lg-2">
             <img data-bind="attr:{src: PosterLogoUrl}" /> 
        </div>
         <div class="col-lg-8">
                <div class="comment-content" style="float:left">
                    
              
                <p  data-bind="html:FullDescription" >
                </p>
                       
                <!-- ko foreach: Pics-->
                    <img data-bind="attr:{src: PicUrl},click:ShowOriginalPic" /> 
                <!-- /ko -->
                    <div>
                             <!-- ko if: Point()!='0' -->
                        <span data-bind="text:Point"></span>  <!-- /ko -->
                    </div>
                </div>
         </div>
         <div class="col-lg-2"></div>
    </div>
    

    <div class="comments_list" data-bind="visible:Comments().length>0">


                 <!-- ko foreach: Comments-->
                 
                    <!-- ko if: IsMyComment -->
       
                 <div class="row comment-row">
                       <div class="col-lg-2"> <img data-bind="attr:{src: CustomerLog}" /> </div>
                    
                     <div class="col-lg-8">
                         
                          <span class="comment-content" data-bind="html:Text" style="float:left"></span>
                         <!-- ko foreach: Pics-->
                         <img data-bind="attr:{src: PicUrl},click:ShowOriginalPic" /> 
                         <!-- /ko -->
                     </div>
                     <div class="col-lg-2"></div>
                 </div>
                 <!-- /ko -->
                 
                 <!-- ko ifnot: IsMyComment -->
                 <div class="row comment-row">
                     <div class="col-lg-2"></div>
                     <div class="col-lg-8 ">
                         <span class="comment-content" data-bind="html:Text" style="float:right"></span>
                         
                         <!-- ko foreach: Pics-->
                         <img data-bind="attr:{src: PicUrl},click:ShowOriginalPic" /> 
                         <!-- /ko -->
                     </div>
                     <div class="col-lg-2"> <img data-bind="attr:{src: CustomerLog}" /> </div>
                 </div>
                 

                 <!-- /ko -->
             <!-- /ko -->

            
        <div class="row"> <div class="col-lg-2"></div>
                     <div class="col-lg-8 ">
            <input type="button" value="More" data-bind="click:MoreComments,visible:Comments().length>0" class="btn btn-default   btn-block" />
                         </div>
        </div>
    </div>


    <div class="status_operation">
        <!-- ko if: IsProduct-->
        <ul class="nav nav-tabs" id="myTab">
            <li class="active"><a href="#statusTab" data-toggle="tab">commment</a></li>
            <li><a href="#prodTab" data-toggle="tab">buy</a></li> 
        </ul>
         <!-- /ko -->
        
        <div class="tab-content">
            <div class="tab-pane active" id="statusTab">
                     <div class="post_inner">
            
                        <textarea data-bind="value:NewComment" class="form-control">
                        </textarea>
                        <a data-bind="click:$root.AddComment" class="status-comment-btn btn btn-primary btn-sm">comment</a>
                        <a data-bind="click:$root.GivePoint" class="status-comment-btn btn btn-primary btn-sm">Point</a>
                    </div>
            </div> 
             <!-- ko if: IsProduct-->
            <div class="tab-pane " id="prodTab">
                <div class="post_inner">
                    
            
              
                <!-- ko foreach: ProductVariantModels -->
                <div> 
                    <span >Price:</span> <span data-bind="text:Price"></span>
                    <span> Quantity:</span> <input type="text" data-bind="value:SelectQuantity" />(<span data-bind="text:Stock"></span>)
                    <a data-bind="click:$root.AddToCart" class="btn btn-primary btn-sm">Add to cart</a>
                </div>
                <!-- /ko -->
                </div>
            </div>
            <!-- /ko -->
        </div>
           
            

        
        </div>


@{
    var model = ViewBag.Model;
    var jsonStr = new HtmlString(new JavaScriptSerializer().Serialize(model));
}

@section scripts
{
    <script type="text/javascript" src="~/Scripts/jquery.signalR-1.1.2.js"></script>
    <script type="text/javascript" src="~/signalr/hubs"></script>

    <script>

        var init = @jsonStr;
        var hub = $.connection.comments;        
    
        
        function StatusPictureModel(picId, picUrl) {

            var self = this;
            self.PicId = ko.observable(picId);
            self.PicUrl = ko.observable(picUrl);
            self.IsOrignalSize = ko.observable(false);
            self.PicSize = ko.observable(80);

            self.ShowOriginalPic = function() {

                if (self.IsOrignalSize() == true) {
                    self.IsOrignalSize(false);
                    self.PicSize(80);
                    $.ajax({
                        url: "/api/PicApi/GetPicUrl",
                        type: 'post',
                        data: ko.toJSON(self),
                        contentType: 'application/json',
                        success: function(result) {

                            self.PicUrl(result.PicUrl);
                        }
                    });
                } else {
                    self.IsOrignalSize(true);
                    self.PicSize(0);
                    $.ajax({
                        url: "/api/PicApi/GetPicUrl",
                        type: 'post',
                        data: ko.toJSON(self),
                        contentType: 'application/json',
                        success: function(result) {

                            self.PicUrl(result.PicUrl);
                        }
                    });
                }

            };
        }
  


        function CommentModel(id, customerLog, commenterId,  text, createdAt, isMyComment) {

            var self = this;
            self.Id= ko.observable(id);
            self.CustomerLog= ko.observable(customerLog);
            self.CommenterId= ko.observable(commenterId);
            self.Text = ko.observable(text);
            self.CreatedAt = ko.observable(createdAt);
            self.IsMyComment= ko.observable(isMyComment);
            self.Pics = ko.observableArray([]);
        }

        function ProductVariantModel(id, stockQuantity, price) {
            var self = this;
            self.Id = ko.observable(id);
            self.Price = ko.observable(price);
            self.Stock = ko.observable(stockQuantity);
            self.SelectQuantity = ko.observable(1);

        }


        function AddToCartProductModel(productVariantId, selectQuantity, pvAttributeValues) {
            var self = this;
            self.ProductVariantId = productVariantId;
            self.Quantity = selectQuantity;
            self.ProductVariantAttributeValueIds = pvAttributeValues;
        }

        function AddCommentModel(statudId, text) {
            var self = this;
            self.StatusId = ko.observable(statudId);
            self.Text = ko.observable(text);
        }
        function PageInfo(statusId, pageIndex, pageSize) {
            var self = this;
            self.StatusId = ko.observable(statusId);
            self.PageIndex= ko.observable(pageIndex);
            self.PageSize= ko.observable(pageSize);
            self.NextPage = function() {
                return new PageInfo(statusId, pageIndex + 1, pageSize);
            };
        }

        function StatusModel() {
            var self = this;
            self.Id = ko.observable(init.Id);
            self.FullDescription = ko.observable(init.Text);
            self.Point = ko.observable(init.Point);
            self.PosterLogoUrl = ko.observable(init.PosterLogoUrl);
            self.IsProduct = ko.observable(init.IsProduct);
            if (init.IsProduct) {
                var tempProductVariants = $.isEmptyObject(init.ProductStatusInfo.PvInfos) ? [] : $.map(init.ProductStatusInfo.PvInfos, function(a) {

                    return new ProductVariantModel(a.ProductVariantId, a.ProductStock, a.ProductPrice);
                });

                self.ProductVariantModels = ko.observableArray(tempProductVariants);
            } else {
                self.ProductVariantModels = ko.observableArray([]);
            }

            var tempPics = $.isEmptyObject(init.Pics) ? [] : $.map(init.Pics, function(p) {
                return new StatusPictureModel(p.PicId, p.PicUrl);
            });
            self.Pics = ko.observableArray(tempPics);

            var tempComments = $.isEmptyObject(init.CommentModels) ? [] : $.map(init.CommentModels, function(a) {
                return new CommentModel(a.Id, a.CustomerLogUrl, a.CommenterId, a.Text,a.CreatedAt, a.IsMyComment);
            });

            self.Comments = ko.observableArray(tempComments);
            self.NewComment = ko.observable();
            self.PageInfo = new PageInfo(init.Id, 0, 5);           

            self.MoreComments = function() {
                self.PageInfo = self.PageInfo.NextPage();

                $.ajax({
                    url: "/api/StatusApi/GetPageComments",
                    type: 'post',
                    async :false,
                    data: ko.toJSON(self.PageInfo),
                    contentType: 'application/json',
                    success: function(result) {

                        if (result.Status == "0") {
                            var commentList = result.CommentList;
                            
                            $.each(commentList, function(index, a) {
                                
                                vm.Comments.push(new CommentModel(a.Id, a.CustomerLogUrl, a.CommenterId, a.Text,a.CreatedAt, a.IsMyComment));
                                
                            });
                            
                        } else {
                        }
                    }
                });
            };
            self.GivePoint = function(c) {
                var request = {
                    StatusId: self.Id(),                  
                };
                $.ajax({
                    url: "/api/StatusApi/GivePointToStatuses",
                    type: 'post',
                    data: ko.toJSON(request),
                    contentType: 'application/json',
                    success: function(result) {

                        if (result.Status == "0") {

                            toastr.success(result.Message);
                            self.Point(result.CurrentPoint);
                        } else {
                            toastr.error(result.Message);
                        }
                    }
                });
            };
            self.AddComment = function(c) {
                var addCommentModel = new AddCommentModel(self.Id(), self.NewComment());

                var message = {
                    Text: self.NewComment(),
                    StatusId: self.Id(),
                };
                
                hub.server.sendComment(message).fail(function(err) {
                });
                
                //$.ajax({
                //    url: "/api/CommentsApi/AddComments",
                //    type: 'post',
                //    data: ko.toJSON(addCommentModel),
                //    contentType: 'application/json',
                //    success: function(result) {

                //        if (result.Status == "0") {
                //            alert("保存成功");
                //        } else {
                //            toastr.error(result.Message);
                //        }
                //    }
                //});
            };
            self.AddToCart = function(pv) {
                var pvValueIds = [];


                //$.each(pv.ProductVariantAttributes(), function (idx, item) {
                //    var selectedAttributeValue = item.SelectedAttributeValue();
                //    pvValueIds.push(selectedAttributeValue.Id());
                //});


                var cartModel = new AddToCartProductModel(pv.Id(), pv.SelectQuantity(), pvValueIds);
                $.ajax({
                    url: "/api/ShoppingCartApi/AddProductVariantToCart",
                    type: 'post',
                    data: ko.toJSON(cartModel),
                    contentType: 'application/json',
                    success: function(result) {

                        if (result.Status == "0") {

                            toastr.success(result.Message);
                        } else {
                            toastr.error(result.Message);
                        }
                    }
                });
            };
        }

        var vm = new StatusModel();


        $(function() {
            hub.client.success = function(a) {
            };

            $.connection.hub.qs = { "StatusId" :init.Id };
            $.connection.hub.start().done(function() {
            });
            
            hub.client.messageReceived = function(a) {

                
                
                vm.Comments.push(new CommentModel(a.Id, a.CustomerLogUrl, a.CommenterId, a.Text,a.CreatedAt, a.IsMyComment));
            };
            ko.applyBindings(vm);

        });

    </script>
}